<template>
  <div class="carousel-list">
    <div class="page-header">
      <h2 class="page-title">轮播</h2>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <el-input 
          v-model="filterForm.title" 
          placeholder="请输入标题关键字"
          class="filter-input"
          clearable
        />
        
        <div class="time-filters">
          <span class="time-label">上传时间：</span>
          <el-date-picker
            v-model="filterForm.createTimeStart"
            type="datetime"
            placeholder="开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            class="time-picker"
          />
          <el-date-picker
            v-model="filterForm.createTimeEnd"
            type="datetime"
            placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            class="time-picker"
          />
        </div>
        
        <el-button type="primary" @click="handleSearch">筛选</el-button>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <div class="action-left">
        <span class="section-title">轮播图列表</span>
        <el-button 
          type="danger" 
          :disabled="selectedRows.length === 0"
          @click="handleBatchDelete"
        >
          批量删除 ({{ selectedRows.length }})
        </el-button>
      </div>
      <div class="action-right">
        <el-button type="primary" @click="handleAdd">新建轮播图</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table 
        :data="tableData" 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        border
        stripe
      >
        <el-table-column type="selection" width="50" align="center" />
        
        <el-table-column prop="title" label="轮播图标题" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <span class="title-cell">{{ scope.row.title || 'banner' }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="预览图" width="120" align="center">
          <template #default="scope">
            <div class="preview-image">
              <img :src="getImageUrl(scope.row)" alt="预览图" @error="handleImageError" />
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="link" label="链接地址" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            <span class="link-cell">{{ scope.row.link || '暂无链接' }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="number" label="排序" width="80" align="center">
          <template #default="scope">
            <el-tag size="small" type="info">{{ scope.row.number || 1 }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="creator" label="上传人" width="100" align="center">
          <template #default="scope">
            <span class="creator-cell">{{ scope.row.creator || 'admin' }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="上传时间" width="180" align="center">
          <template #default="scope">
            <span class="time-cell">{{ formatDateTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <div class="pagination-info">
        <span class="info-text">
          共{{ pagination.total }}条/{{ pagination.totalPages }}页数据
        </span>
      </div>
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="prev, pager, next, sizes, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增轮播图对话框 -->
    <el-dialog 
      v-model="addDialogVisible" 
      title="新增轮播图" 
      width="600px" 
      :before-close="handleCloseAddDialog"
    >
      <el-form 
        :model="addForm" 
        :rules="addFormRules" 
        ref="addFormRef" 
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="addForm.title" 
            placeholder="请输入轮播图标题"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="轮播图片" prop="image" required>
          <div class="upload-container">
            <el-upload
              ref="uploadRef"
              class="image-uploader"
              :action="''"
              :http-request="handleImageUpload"
              :before-upload="beforeImageUpload"
              :show-file-list="false"
              :disabled="imageUploading"
            >
              <div v-if="addForm.image" class="image-preview">
                <img :src="addForm.image" alt="预览图" />
                <div class="image-overlay">
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click.stop="removeImage"
                    circle
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
              <div v-else class="upload-placeholder">
                <el-icon class="upload-icon" v-if="!imageUploading"><Plus /></el-icon>
                <el-icon class="upload-icon is-loading" v-else><Loading /></el-icon>
                <div class="upload-text">{{ imageUploading ? '上传中...' : '点击上传图片' }}</div>
              </div>
            </el-upload>
          </div>
        </el-form-item>
        
        <el-form-item label="链接地址" prop="link">
          <el-input 
            v-model="addForm.link" 
            placeholder="请输入轮播图链接地址"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="排序序号" prop="number">
          <el-input-number 
            v-model="addForm.number" 
            :min="1" 
            :max="999"
            placeholder="请输入排序序号"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-switch 
            v-model="addForm.status"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAddDialog">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmitAdd"
            :loading="submitting"
          >
            {{ submitting ? '提交中...' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑轮播图对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑轮播图" 
      width="600px" 
      :before-close="handleCloseEditDialog"
    >
      <el-form 
        :model="editForm" 
        :rules="editFormRules" 
        ref="editFormRef" 
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="editForm.title" 
            placeholder="请输入轮播图标题"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="轮播图片" prop="image" required>
          <div class="upload-container">
            <el-upload
              ref="editUploadRef"
              class="image-uploader"
              :action="''"
              :http-request="handleEditImageUpload"
              :before-upload="beforeImageUpload"
              :show-file-list="false"
              :disabled="editImageUploading"
            >
              <div v-if="editForm.image" class="image-preview">
                <img :src="editForm.image" alt="预览图" />
                <div class="image-overlay">
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click.stop="removeEditImage"
                    circle
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
              <div v-else class="upload-placeholder">
                <el-icon class="upload-icon" v-if="!editImageUploading"><Plus /></el-icon>
                <el-icon class="upload-icon is-loading" v-else><Loading /></el-icon>
                <div class="upload-text">{{ editImageUploading ? '上传中...' : '点击上传图片' }}</div>
              </div>
            </el-upload>
          </div>
        </el-form-item>
        
        <el-form-item label="链接地址" prop="link">
          <el-input 
            v-model="editForm.link" 
            placeholder="请输入轮播图链接地址"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="排序序号" prop="number">
          <el-input-number 
            v-model="editForm.number" 
            :min="1" 
            :max="999"
            placeholder="请输入排序序号"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-switch 
            v-model="editForm.status"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseEditDialog">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmitEdit"
            :loading="editSubmitting"
          >
            {{ editSubmitting ? '更新中...' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, Delete, Loading } from '@element-plus/icons-vue'
import { getCarouselList } from '@/http/axiosRead'
import { uploadFile, addCarousel, updateCarousel, deleteCarousels } from '@/http/axiosWrtie'
import type { UploadProps, UploadFile, FormInstance, UploadRequestOptions } from 'element-plus'

// 筛选表单
const filterForm = reactive({
  title: '',
  createTimeStart: '',
  createTimeEnd: ''
})

// 定义轮播图数据类型
interface CarouselItem {
  id: number
  title: string
  imageUrl?: string
  image?: string
  link?: string
  number?: number
  status: boolean
  creator: string
  createTime: string
  createPeople?: string
  updatePeople?: string
  updateTime?: string
}

// 表格数据
const tableData = ref<CarouselItem[]>([])
const loading = ref(false)
const selectedRows = ref<CarouselItem[]>([])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  totalPages: 0
})

// 新增弹出框相关
const addDialogVisible = ref(false)
const addFormRef = ref<FormInstance>()
const imageUploading = ref(false)
const submitting = ref(false)

// 编辑弹出框相关
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editImageUploading = ref(false)
const editSubmitting = ref(false)
const currentEditId = ref<number>(0)

// 新增表单数据
const addForm = reactive({
  title: '',
  image: '',
  link: '',
  number: 1,
  status: true
})

// 编辑表单数据
const editForm = reactive({
  id: 0,
  title: '',
  image: '',
  link: '',
  number: 1,
  status: true
})

// 表单验证规则
const addFormRules = reactive({
  title: [
    { required: true, message: '请输入轮播图标题', trigger: 'blur' },
    { min: 1, max: 50, message: '标题长度在1到50个字符之间', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传轮播图片', trigger: 'change' }
  ],
  link: [
    { required: true, message: '请输入链接地址', trigger: 'blur' },
    { type: 'url', message: '请输入正确的URL格式', trigger: 'blur' }
  ],
  number: [
    { required: true, message: '请输入排序序号', trigger: 'blur' },
    { type: 'number', min: 1, max: 999, message: '序号必须在1-999之间', trigger: 'blur' }
  ]
})

// 编辑表单验证规则
const editFormRules = reactive({
  title: [
    { required: true, message: '请输入轮播图标题', trigger: 'blur' },
    { min: 1, max: 50, message: '标题长度在1到50个字符之间', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传轮播图片', trigger: 'change' }
  ],
  link: [
    { required: true, message: '请输入链接地址', trigger: 'blur' },
    { type: 'url', message: '请输入正确的URL格式', trigger: 'blur' }
  ],
  number: [
    { required: true, message: '请输入排序序号', trigger: 'blur' },
    { type: 'number', min: 1, max: 999, message: '序号必须在1-999之间', trigger: 'blur' }
  ]
})

// 获取轮播图列表
const getCarouselData = async () => {
  loading.value = true
  try {
    const params = {
      Title: filterForm.title || undefined,
      CreateTimeStart: filterForm.createTimeStart || undefined,
      CreateTimeEnd: filterForm.createTimeEnd || undefined,
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    
    const response = await getCarouselList(params)
    
    // 解析返回数据
    if (response.data && response.data.code === 200 && response.data.data) {
      // 使用实际返回的数据
      tableData.value = response.data.data.map((item: any) => ({
        id: item.id,
        title: item.title,
        image: item.image,
        imageUrl: item.image, // 兼容字段
        link: item.link,
        number: item.number,
        status: item.status,
        creator: item.createPeople || item.updatePeople || 'admin',
        createTime: item.createTime
      }))
      
      // 使用返回的总数和总页数
      pagination.total = response.data.totaCount || 0
      pagination.totalPages = response.data.totaPage || 0
      
      console.log('轮播图数据加载成功:', {
        总数量: response.data.totaCount,
        总页数: response.data.totaPage,
        当前页数据: tableData.value.length
      })
    } else {
      // 如果返回格式不正确，使用模拟数据
      console.warn('返回数据格式不正确，使用模拟数据')
      const mockData = Array.from({ length: 3 }, (_, index) => ({
        id: index + 1,
        title: index === 0 ? 'new' : index === 1 ? '哈哈' : '喜喜',
        image: 'http://101.201.170.32:9000/images/09a6f2bd-1b67-463e-b4e9-050baa992e74_FCA1BF6E5F171DF73E86FFAA0798D107.jpg',
        imageUrl: 'http://101.201.170.32:9000/images/09a6f2bd-1b67-463e-b4e9-050baa992e74_FCA1BF6E5F171DF73E86FFAA0798D107.jpg',
        link: index === 0 ? '测试链接' : 'http://101.201.170.32:9000/images/09a6f2bd-1b67-463e-b4e9-050baa992e74_FCA1BF6E5F171DF73E86FFAA0798D107.jpg',
        number: index + 1,
        status: true,
        creator: 'admin',
        createTime: `2025-08-01T0${8 + index}:${String(25 + index * 34).padStart(2, '0')}:${String(22 + index * 20)}.${String(89894 + index * 10000)}`
      }))
      tableData.value = mockData
      pagination.total = 3
      pagination.totalPages = 1
    }
  } catch (error) {
    console.error('获取轮播图列表失败:', error)
    ElMessage.error('获取轮播图列表失败')
    
    // 使用模拟数据作为降级方案
    const mockData = Array.from({ length: 3 }, (_, index) => ({
      id: index + 1,
      title: index === 0 ? 'new' : index === 1 ? '哈哈' : '喜喜',
      image: 'http://101.201.170.32:9000/images/09a6f2bd-1b67-463e-b4e9-050baa992e74_FCA1BF6E5F171DF73E86FFAA0798D107.jpg',
      imageUrl: 'http://101.201.170.32:9000/images/09a6f2bd-1b67-463e-b4e9-050baa992e74_FCA1BF6E5F171DF73E86FFAA0798D107.jpg',
      link: index === 0 ? '测试链接' : 'http://101.201.170.32:9000/images/09a6f2bd-1b67-463e-b4e9-050baa992e74_FCA1BF6E5F171DF73E86FFAA0798D107.jpg',
      number: index + 1,
      status: true,
      creator: 'admin',
      createTime: `2025-08-01T0${8 + index}:${String(25 + index * 34).padStart(2, '0')}:${String(22 + index * 20)}.${String(89894 + index * 10000)}`
    }))
    tableData.value = mockData
    pagination.total = 3
    pagination.totalPages = 1
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getCarouselData()
}



// 新建轮播图
const handleAdd = () => {
  addDialogVisible.value = true
  resetAddForm()
}

// 编辑轮播图
const handleEdit = (row: CarouselItem) => {
  currentEditId.value = row.id
  editForm.id = row.id
  editForm.title = row.title
  editForm.image = getImageUrl(row)
  editForm.link = row.link || ''
  editForm.number = row.number || 1
  editForm.status = row.status
  
  // 重置上传状态
  editImageUploading.value = false
  
  editDialogVisible.value = true
}

// 删除轮播图
const handleDelete = async (row: CarouselItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除轮播图 "${row.title}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 调用删除接口
    const response = await deleteCarousels({
      ids: [row.id],
      updatePeople: 'admin' // 这里可以从用户信息中获取
    })
    
    if (response.data && response.data.message) {
      ElMessage.success(response.data.message)
      getCarouselData()
    } else {
      ElMessage.success('删除成功')
      getCarouselData()  
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除轮播图失败:', error)
      ElMessage.error('删除轮播图失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的轮播图')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个轮播图吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 调用批量删除接口
    const ids = selectedRows.value.map(item => item.id)
    const response = await deleteCarousels({
      ids: ids,
      updatePeople: 'admin' // 这里可以从用户信息中获取
    })
    
    if (response.data && response.data.message) {
      ElMessage.success(response.data.message)
    } else {
      ElMessage.success(`批量删除成功，共删除 ${ids.length} 个轮播图`)
    }
    
    // 清空选择
    selectedRows.value = []
    
    // 刷新列表
    getCarouselData()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量删除轮播图失败:', error)
      ElMessage.error('批量删除轮播图失败')
    }
  }
}

// 选择变化
const handleSelectionChange = (selection: CarouselItem[]) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  getCarouselData()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  getCarouselData()
}

// 重置新增表单
const resetAddForm = () => {
  addForm.title = ''
  addForm.image = ''
  addForm.link = ''
  addForm.number = 1
  addForm.status = true
  addFormRef.value?.clearValidate()
}

// 关闭新增对话框
const handleCloseAddDialog = () => {
  addDialogVisible.value = false
  resetAddForm()
}

// 上传前验证
const beforeImageUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理图片上传
const handleImageUpload = async (options: UploadRequestOptions) => {
  imageUploading.value = true
  try {
    // 调用上传文件接口
    const response = await uploadFile(options.file as File)
    
    // 根据返回的数据结构调整这里的路径
    if (response.data && response.data.url) {
      addForm.image = response.data.url
    } else if (response.data && response.data.data) {
      addForm.image = response.data.data
    } else if (response.data) {
      // 如果直接返回URL字符串
      addForm.image = response.data
    } else {
      // 如果接口返回格式不明确，使用模拟URL（开发环境）
      const timestamp = Date.now()
      addForm.image = `http://101.201.170.32:9000/images/add_${timestamp}_${options.file.name}`
    }
    
    ElMessage.success('图片上传成功')
    // 手动触发表单验证
    addFormRef.value?.validateField('image')
  } catch (error) {
    console.error('新增图片上传失败:', error)
    ElMessage.error('图片上传失败，请重试')
  } finally {
    imageUploading.value = false
  }
}

// 移除图片
const removeImage = () => {
  addForm.image = ''
  addFormRef.value?.validateField('image')
}

// 提交新增表单
const handleSubmitAdd = async () => {
  if (!addFormRef.value) return
  
  try {
    const valid = await addFormRef.value.validate()
    if (!valid) return
    
    submitting.value = true
    
    const submitData = {
      title: addForm.title,
      image: addForm.image,
      link: addForm.link,
      number: addForm.number,
      status: addForm.status,
      createPeople: 'admin' // 这里可以从用户信息中获取
    }
    
    const response = await addCarousel(submitData)
    
    if (response.data && response.data.id) {
      ElMessage.success(response.data.message || '轮播图创建成功')
      addDialogVisible.value = false
      resetAddForm()
      // 刷新列表
      getCarouselData()
    } else {
      ElMessage.error('创建失败')
    }
  } catch (error) {
    console.error('创建轮播图失败:', error)
    ElMessage.error('创建轮播图失败')
  } finally {
    submitting.value = false
  }
}

// 重置编辑表单
const resetEditForm = () => {
  editForm.id = 0
  editForm.title = ''
  editForm.image = ''
  editForm.link = ''
  editForm.number = 1
  editForm.status = true
  editFormRef.value?.clearValidate()
}

// 关闭编辑对话框
const handleCloseEditDialog = () => {
  editDialogVisible.value = false
  resetEditForm()
}

// 处理编辑图片上传
const handleEditImageUpload = async (options: UploadRequestOptions) => {
  editImageUploading.value = true
  try {
    // 调用上传文件接口
    const response = await uploadFile(options.file as File)
    
    // 根据返回的数据结构调整这里的路径
    if (response.data && response.data.url) {
      editForm.image = response.data.url
    } else if (response.data && response.data.data) {
      editForm.image = response.data.data
    } else if (response.data) {
      // 如果直接返回URL字符串
      editForm.image = response.data
    } else {
      // 如果接口返回格式不明确，使用模拟URL（开发环境）
      const timestamp = Date.now()
      editForm.image = `http://101.201.170.32:9000/images/edit_${timestamp}_${options.file.name}`
    }
    
    ElMessage.success('图片上传成功')
    // 手动触发表单验证
    editFormRef.value?.validateField('image')
  } catch (error) {
    console.error('编辑图片上传失败:', error)
    ElMessage.error('图片上传失败，请重试')
  } finally {
    editImageUploading.value = false
  }
}

// 移除编辑图片
const removeEditImage = () => {
  editForm.image = ''
  editFormRef.value?.validateField('image')
}

// 提交编辑表单
const handleSubmitEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    const valid = await editFormRef.value.validate()
    if (!valid) return
    
    editSubmitting.value = true
    
    const submitData = {
      id: editForm.id,
      title: editForm.title,
      image: editForm.image,
      link: editForm.link,
      number: editForm.number,
      status: editForm.status,
      updatePeople: 'admin' // 这里可以从用户信息中获取
    }
    
    const response = await updateCarousel(submitData)
    
    if (response.data && response.data.message) {
      ElMessage.success(response.data.message)
      editDialogVisible.value = false
      resetEditForm()
      // 刷新列表
      getCarouselData()
    } else {
      ElMessage.success('轮播图更新成功')
      editDialogVisible.value = false
      resetEditForm()
      getCarouselData()
    }
  } catch (error) {
    console.error('更新轮播图失败:', error)
    ElMessage.error('更新轮播图失败')
  } finally {
    editSubmitting.value = false
  }
}

// 获取图片URL
const getImageUrl = (row: CarouselItem) => {
  return row.image || row.imageUrl || '/src/assets/logo.svg'
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/src/assets/logo.svg'
}

// 获取状态显示文本
const getStatusText = (status: boolean) => {
  return status ? '上架' : '下架'
}

// 获取状态标签类型
const getStatusType = (status: boolean) => {
  return status ? 'success' : 'info'
}

// 格式化时间为年月日时分秒
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '2020-02-07 21:00:00'
  
  try {
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) {
      // 如果日期无效，返回原始字符串
      return dateTime
    }
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    // 如果格式化失败，返回原始字符串
    return dateTime
  }
}

// 初始化
onMounted(() => {
  getCarouselData()
})
</script>

<style scoped>
.carousel-list {
  padding: 20px;
  background: #f5f5f5;
  min-height: 55vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  color: #333;
  margin: 0;
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.filter-input {
  width: 300px;
}

.time-filters {
  display: flex;
  align-items: center;
  gap: 10px;
}

.time-label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.time-picker {
  width: 180px;
}

.action-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.action-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.table-section :deep(.el-table) {
  border-radius: 8px;
}

.table-section :deep(.el-table__header) {
  background-color: #fafafa;
}

.table-section :deep(.el-table__header th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
}

.table-section :deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

.table-section :deep(.el-table__body td) {
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
}

.preview-image {
  width: 80px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 6px;
  overflow: hidden;
  margin: 0 auto;
  border: 1px solid #e4e7ed;
}

.preview-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.preview-image:hover img {
  transform: scale(1.05);
}

.title-cell {
  font-weight: 500;
  color: #303133;
}

.link-cell {
  color: #606266;
  word-break: break-all;
}

.creator-cell {
  color: #606266;
  font-size: 13px;
}

.time-cell {
  color: #909399;
  font-size: 12px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-buttons .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 0 20px;
}

.pagination-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.info-text {
  font-size: 14px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .filter-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .time-filters {
    flex-wrap: wrap;
  }
}

@media (max-width: 768px) {
  .carousel-list {
    padding: 10px;
  }
  
  .filter-input,
  .time-picker {
    width: 100%;
  }
  
  .action-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .pagination-section {
    flex-direction: column;
    gap: 15px;
    align-items: center;
  }
  
  /* 移动端表格优化 */
  .table-section :deep(.el-table) {
    font-size: 12px;
  }
  
  .preview-image {
    width: 60px;
    height: 40px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
  
  .action-buttons .el-button {
    padding: 2px 6px;
    font-size: 11px;
  }
}

@media (max-width: 480px) {
  .table-section {
    overflow-x: auto;
  }
  
  .table-section :deep(.el-table) {
    min-width: 600px;
  }
}

/* 新增弹出框样式 */
.upload-container {
  width: 100%;
}

.image-uploader {
  width: 100%;
}

.image-preview {
  position: relative;
  width: 200px;
  height: 120px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-preview:hover .image-overlay {
  opacity: 1;
}

.upload-placeholder {
  width: 200px;
  height: 120px;
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.upload-placeholder:hover {
  border-color: #409eff;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.upload-icon.is-loading {
  animation: rotating 2s linear infinite;
}

.upload-text {
  color: #8c939d;
  font-size: 14px;
}

.dialog-footer {
  text-align: right;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>